package com.ruoyi.matrix.service;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class RequestUtils {
    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;

    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url, String contentType) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-type", contentType);
        httpGet.setHeader("Cache-Control", "no-cache");

        // 装载配置信息
        httpGet.setConfig(config);

        // 发起请求
        CloseableHttpResponse response = httpClient.execute(httpGet);

        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        return null;
    }

    public String doPost(String url, String json, String contentType) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);

        httpPost.setHeader("Content-type", contentType);
        httpPost.setHeader("Cache-Control", "no-cache");


        StringEntity s = new StringEntity(json, StandardCharsets.UTF_8.name());
        s.setContentEncoding(StandardCharsets.UTF_8.name());
        // 发送json数据需要设置contentType
        s.setContentType(contentType);
        httpPost.setEntity(s);

        // 发起请求
        CloseableHttpResponse response = null;
        try {
            synchronized (this.httpClient) {
                response = this.httpClient.execute(httpPost);
            }
        } catch (Exception e) {
            throw e;
        }

        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        if (response.getStatusLine().getStatusCode() == 200) {
            return result;
        } else {
            throw new Exception(result);
        }

    }

}